// pages/orderDetail/orderDetail.js
const requestHelper = require('../../utils/request');
const buildUrl = requestHelper.buildUrl || ((url) => url);

// 校园内常用地点坐标映射，用于在接口未返回经纬度时兜底展示地图
const LOCATION_COORD_MAP = [
  { keyword: '校园邮局', lat: 23.032689712755, lng: 112.18377894877881 },
  { keyword: '邮局', lat: 23.032689712755, lng: 112.18377894877881 },
  { keyword: '11栋', lat: 23.03238555003609, lng: 112.18528494987049 },
  { keyword: '12栋', lat: 23.03185541273769, lng: 112.18663646893276 },
  { keyword: '13栋', lat: 23.031121373163103, lng: 112.18840895309461 },
  { keyword: '8栋', lat: 23.031039812980925, lng: 112.18468673647578 },
  { keyword: '9栋', lat: 23.030590683981806, lng: 112.18670323435379 },
  { keyword: '饭堂', lat: 23.02955078350187, lng: 112.1877445687046 },
  { keyword: '食堂', lat: 23.02955078350187, lng: 112.1877445687046 },
  { keyword: '图书馆', lat: 23.027613692787398, lng: 112.18679185855467 },
  { keyword: '丰巢', lat: 23.024779373141513, lng: 112.18377863571686 },
  { keyword: '妈妈驿站', lat: 23.024779373141513, lng: 112.18377863571686 },
  { keyword: '一期宿舍', lat: 23.024779373141513, lng: 112.18377863571686 }
];

function findLocationCoord(text) {
  if (!text) return null;
  const content = String(text);
  for (const item of LOCATION_COORD_MAP) {
    if (content.indexOf(item.keyword) !== -1) {
      return { lat: item.lat, lng: item.lng };
    }
  }
  return null;
}

Page({

  /**
   * 页面的初始数据
   */
  data: {
    orderId: null,
    role: 'order_user',
    order: null
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    const orderId = Number(options.orderId || 0);
    const role = options.role || 'order_user';
    if (!orderId) {
      wx.showToast({ title: '订单不存在', icon: 'none' });
      return;
    }
    this.setData({ orderId, role });
    this.loadOrder();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  onShow() {
    if (this.data.orderId) this.loadOrder();
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {
    this.loadOrder(() => wx.stopPullDownRefresh());
  },

  // 状态文本映射
  getStatusText(status) {
    const map = {
      1: '待接单',
      2: '已接单',
      3: '已取件',
      4: '送达中',
      5: '已完成',
      6: '已取消'
    };
    return map[status] || `状态 ${status || ''}`;
  },

  // 时间格式化
  formatTime(timestamp) {
    if (!timestamp) return '';
    const date = new Date(timestamp);
    if (Number.isNaN(date.getTime())) return timestamp;
    const y = date.getFullYear();
    const m = String(date.getMonth() + 1).padStart(2, '0');
    const d = String(date.getDate()).padStart(2, '0');
    const hh = String(date.getHours()).padStart(2, '0');
    const mm = String(date.getMinutes()).padStart(2, '0');
    return `${y}-${m}-${d} ${hh}:${mm}`;
  },

  loadOrder(done) {
    const { orderId } = this.data;
    wx.request({
      url: buildUrl(`/api/orders/${orderId}`),
      method: 'GET',
      success: (res) => {
        const data = res.data || {};
        if (data.success) {
          const raw = data.data || {};
          const enhanced = {
            ...raw,
            status_text: this.getStatusText(raw.status),
            created_at_formatted: this.formatTime(raw.created_at),
            delivery_time_formatted: this.formatTime(raw.delivery_time)
          };
          this.setData({ order: enhanced });
        }
      },
      complete: () => {
        if (typeof done === 'function') done();
      }
    });
  },

  goBack() {
    wx.navigateBack();
  },

  // 在地图中查看取件点
  viewPickupOnMap() {
    const order = this.data.order;
    if (!order) {
      wx.showToast({ title: '订单未加载', icon: 'none' });
      return;
    }

    let lat = Number(order.pickup_lat);
    let lng = Number(order.pickup_lng);

    // 如果接口未返回坐标，尝试根据取件点文字匹配预置地点
    if ((!lat || !lng || Number.isNaN(lat) || Number.isNaN(lng)) && order.pickup_location) {
      const mapped = findLocationCoord(order.pickup_location);
      if (mapped) {
        lat = mapped.lat;
        lng = mapped.lng;
      }
    }

    if (!lat || !lng || Number.isNaN(lat) || Number.isNaN(lng)) {
      wx.showToast({ title: '暂无取件点坐标', icon: 'none' });
      return;
    }

    wx.openLocation({
      latitude: lat,
      longitude: lng,
      name: '取件点',
      address: order.pickup_location || '取件地点',
      scale: 18
    });
  },

  // 在地图中查看送达点
  viewDropOnMap() {
    const order = this.data.order;
    if (!order) {
      wx.showToast({ title: '订单未加载', icon: 'none' });
      return;
    }

    let lat = Number(order.drop_lat);
    let lng = Number(order.drop_lng);

    // 如果接口未返回坐标，尝试根据送达点文字匹配预置地点
    if ((!lat || !lng || Number.isNaN(lat) || Number.isNaN(lng)) && order.delivery_address) {
      let mapped = findLocationCoord(order.delivery_address);

      // 如果直接匹配不到，尝试从地址前缀提取宿舍栋数（例如“9-305”→“9栋”）
      if (!mapped) {
        const addr = String(order.delivery_address);
        const match = addr.match(/^(\d+)[-栋号室]/); // 匹配以数字开头的宿舍号
        if (match && match[1]) {
          const buildingKeyword = `${match[1]}栋`;
          mapped = findLocationCoord(buildingKeyword);
        }
      }

      if (mapped) {
        lat = mapped.lat;
        lng = mapped.lng;
      }
    }

    if (!lat || !lng || Number.isNaN(lat) || Number.isNaN(lng)) {
      wx.showToast({ title: '暂无送达点坐标', icon: 'none' });
      return;
    }

    wx.openLocation({
      latitude: lat,
      longitude: lng,
      name: '送达点',
      address: order.delivery_address || '送达地点',
      scale: 18
    });
  },

  // 联系对方（下单者联系代拿员，或代拿员联系下单者）
  contactOther() {

    const app = getApp();
    const me = app.globalData && app.globalData.userId;
    if (!me) {
      wx.reLaunch({ url: '/pages/login/login' });
      return;
    }

    const { order, role, orderId } = this.data;
    if (!order) {
      wx.showToast({ title: '订单未加载', icon: 'none' });
      return;
    }

    // 订单结束后禁止继续发起会话（已完成/已取消）
    const status = Number(order.status);
    if (status === 5 || status === 6) {
      wx.showToast({ title: '订单已结束，无法继续聊天', icon: 'none' });
      return;
    }

    let otherId = 0;
    if (role === 'order_user') {
      otherId = Number(order.courier_user_id || order.courier_user || 0);
      if (!otherId) {
        wx.showToast({ title: '暂无接单人', icon: 'none' });
        return;
      }
    } else {
      otherId = Number(order.order_user_id || order.order_user || 0);
      if (!otherId) {
        wx.showToast({ title: '无法获取下单者', icon: 'none' });
        return;
      }
    }

    wx.request({
      url: buildUrl('/api/messages/conversations'),
      method: 'POST',
      header: { 'Content-Type': 'application/json' },
      data: {
        participants: [me, otherId],
        order_id: Number(orderId),
        type: 1
      },
      success: (res) => {
        const data = res.data || {};
        const cid = data.data && data.data.id;
        if (!cid) {
          wx.showToast({ title: '无法创建会话', icon: 'none' });
          return;
        }
        wx.navigateTo({ url: `/pages/chat/chat?cid=${cid}&orderId=${orderId}` });
      },
      fail: () => {
        wx.showToast({ title: '发起对话失败', icon: 'none' });
      }
    });
  }
})